package com.vpen.iot.server;

import javax.websocket.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;

@ClientEndpoint
public class WebSocketClient {
    private FileOutputStream fileOutputStream;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to server");
        try {
            fileOutputStream = new FileOutputStream("output.mp4");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(ByteBuffer message) {
        try {
            byte[] bytes = new byte[message.remaining()];
            message.get(bytes);
            fileOutputStream.write(bytes);
            System.out.println("Received " + bytes.length + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Connection closed");
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void connect(String uri) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            container.connectToServer(this, new URI(uri));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        WebSocketClient client = new WebSocketClient();
        String uri = "wss://xy3jsdecoder.ys7.com:20006/playback?dev=AY3069149&serial=AY3069149&chn=1&stream=1&begin=20240806000000&end=20240806000030";
        client.connect(uri);
    }
}
